package com.szy.news.activity;

/**
 * @author 辛晓博
 * 注册实现
 * */

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.szy.news.control.MyApplication;
import com.szy.news.util.ToMD5;
import com.szy.news.util.URL;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
//import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class RegistActivity extends Activity implements OnClickListener {

	private TextView regist_back;
	private TextView tv_regist;
	private EditText et_username_edit;
	private EditText et_password_edit;
	private EditText et_repeat_edit;
	private ProgressDialog pd;// 定义dialog等待
	
	private static final int REQUEST_TIMEOUT = 5 * 1000;// 设置请求超时10秒钟
	private static final int SO_TIMEOUT = 10 * 1000; // 设置等待数据超时时间10秒钟
//	private static final int LOGIN_OK = 1;
	private String responseMsg = ""; 
	
	public MyApplication my_regist;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.registeruser);

		regist_back = (TextView) findViewById(R.id.regist_back);
		regist_back.setOnClickListener(this);
		tv_regist = (TextView) findViewById(R.id.regist_btn);
		tv_regist.setOnClickListener(this);
		et_username_edit = (EditText) findViewById(R.id.username_edit);
		et_username_edit.setOnClickListener(this);
		et_password_edit = (EditText) findViewById(R.id.password_edit);
		et_password_edit.setOnClickListener(this);
		et_repeat_edit = (EditText) findViewById(R.id.repeat_edit);
		et_repeat_edit.setOnClickListener(this);
	}

//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.regist, menu);
//		return true;
//	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		final Intent intent;
//		Intent intent = new Intent();
		if (id == R.id.regist_back) {
			intent = new Intent(RegistActivity.this, LoginActivity.class);
			startActivity(intent);
			finish();
		} else if (id == R.id.regist_btn) {
			RegisterUser();
		} else if (id == R.id.username_edit) {

		} else if (id == R.id.password_edit) {

		} else if (id == R.id.repeat_edit) {

		}
	}

	public void RegisterUser() {
		if (et_username_edit.getText().toString().trim().equals("")
				|| et_username_edit.getText().toString().length() > 20
				|| et_username_edit.getText().toString().trim().length() < 4) {
			Toast.makeText(this, "用户名介于4到20字符之间", Toast.LENGTH_SHORT).show();
			
		} else if (et_password_edit.getText().toString().trim().equals("")
				|| et_password_edit.getText().toString().length() < 4
				|| et_password_edit.getText().toString().length() > 16) {
			Toast.makeText(this, "密码介于4到16个字符之间", Toast.LENGTH_SHORT).show();
		} else if (!et_repeat_edit.getText().toString().trim()
				.equals(et_password_edit.getText().toString().trim())) {
			Toast.makeText(this, "两次密码不一致请重试！", Toast.LENGTH_SHORT).show();
		} else {
			pd = new ProgressDialog(this);
			pd.setMessage("注册中，请稍后...");
			pd.setCancelable(true);
			pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			pd.show();
			new Thread(new RegisterThread()).start();

		}
	}

	// 初始化HttpClient，并设置超时
	public HttpClient getHttpClient() {
		BasicHttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
		HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
		HttpClient client = new DefaultHttpClient(httpParams);
		return client;
	}

	public boolean registerServer(String username, String password) {
		boolean loginValidate = false;
		// 使用apache HTTP客户端实现  
//		String urlStr = "http://192.168.137.1:8080/web/RegisterServlet";
		HttpPost request = new HttpPost(URL.register_urlStr);
		// 如果传递参数多的话，可以对传递的参数进行封装
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 添加用户名和密码
		params.add(new BasicNameValuePair("username", username));
		params.add(new BasicNameValuePair("password", password));
		try {
			// 设置请求参数项 
			request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			HttpClient client = getHttpClient();
			// 执行请求返回相应
			HttpResponse response = client.execute(request);

			// 判断是否请求成功  
			if (response.getStatusLine().getStatusCode() == 200) {
				loginValidate = true;
				// 获得响应信息
				responseMsg = EntityUtils.toString(response.getEntity());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return loginValidate;
	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				pd.cancel();
				Bundle bundle = new Bundle();
				bundle.putString("username", et_username_edit.getText()
						.toString());
				bundle.putString("password", et_password_edit.getText()
						.toString());
				
				
				Intent intent = new Intent();
				intent.putExtras(bundle);
				// 返回intent 
				setResult(RESULT_OK, intent);
				//1-7
				my_regist=(MyApplication) RegistActivity.this.getApplication();
				my_regist.setUsername(et_username_edit.getText().toString().trim());
				my_regist.setFlag(true);
//				Toast.makeText(RegistActivity.this, ""+my_regist.getUsername(), 1000).show();
				intent = new Intent(RegistActivity.this,NewsDetailsActivity.class);
				RegistActivity.this.finish();				
				Toast.makeText(RegistActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
				
				break;
			case 1:
				pd.cancel();
				Toast.makeText(getApplicationContext(), "注册失败,此用户名已存在",
						Toast.LENGTH_SHORT).show();
				break;
			case 2:
				pd.cancel();
				Toast.makeText(getApplicationContext(), "连接服务器失败",
						Toast.LENGTH_SHORT).show();
				break;

			}

		}
	};

	// RegisterThread线程类 
	class RegisterThread implements Runnable {

		@Override
		public void run() {
			String username = et_username_edit.getText().toString();
			String password = ToMD5.md5(et_password_edit.getText().toString());
						
			
			// URL合法，但是这一步并不验证密码是否正确 
			boolean registerValidate = registerServer(username, password);
			Message msg = handler.obtainMessage();
			if (registerValidate) {
				if (responseMsg.equals("success")) {
					msg.what = 0;
					handler.sendMessage(msg);
				} else {
					msg.what = 1;
					handler.sendMessage(msg);
				}

			} else {
				msg.what = 2;
				handler.sendMessage(msg);
			}
		}

	}
}
